package com.cuixichang.minimalism.acl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cuixichang.minimalism.basal.base.Validate;
import com.cuixichang.minimalism.basal.enums.IsEnableEnum;
import com.cuixichang.minimalism.basal.enums.SubassemblyTypeEnum;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;


@Component
public class NumberAreaSubassemblyDesign extends SubassemblyDesignAbs{

    @Override
    public SubassemblyTypeEnum getType() {
        return SubassemblyTypeEnum.Number;
    }

    @Override
    public String example() {
        return "{\"min\":0,\"max\":10}";
    }

    @Override
    public Validate structureValidate(String structure) {
        boolean isJsonObj = JSONUtil.isJsonObj(structure);
        if(!isJsonObj) return  Validate.builder().checked(false).message("数字框阈值预设检测不通过").build();
        JSONObject jsonObject = JSONUtil.parseObj(structure);
        Set<String> keys = jsonObject.keySet();
        boolean matchSize = keys.size() == 2;
        if(!matchSize) return  Validate.builder().checked(false).message("数字框阈值预设检测不通过").build();
        boolean match = keys.containsAll(Arrays.asList("min", "max"));
        if(!match) return  Validate.builder().checked(false).message("数字框阈值预设检测不通过").build();
        Object min = jsonObject.get("min");
        boolean minMatch = min instanceof Number;
        if(!minMatch) return  Validate.builder().checked(false).message("数字框阈值预设检测不通过").build();
        Object max = jsonObject.get("max");
        boolean maxMatch = max instanceof Number;
        if(!maxMatch) return  Validate.builder().checked(false).message("数字框阈值预设检测不通过").build();
        BigDecimal subtract = new BigDecimal(String.valueOf(max)).subtract(new BigDecimal(String.valueOf(min)));
        boolean check = subtract.longValue() >= 0L;
        if(!check) return  Validate.builder().checked(false).message("数字框阈值预设检测不通过").build();
        return Validate.builder().checked(true).message(IsEnableEnum.YES.getDesc()).build();
    }

    @Override
    public Validate valueValidate(String structure, String value) {
         return Validate.builder().checked(true).message(IsEnableEnum.YES.getDesc()).build();
    }

    @Override
    public String previewValue(String structure, Object value) {
        return Objects.nonNull(value)?String.valueOf(value): StrUtil.EMPTY;
    }

    @Override
    public Object resultValue(String value) {
        return value;
    }

    @Override
    public String resultValue(Object value) {
        return String.valueOf(value);
    }
}
